home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 2 / Apprentice-Release2.iso / Tools / MPW / sed 2.0.3 / getopt.c < prev    next >
Encoding:
Text File  |  1994-01-19  |  21.1 KB  |  536 lines  |  [TEXT/MPS ]

  1. /* Getopt for GNU.
  2.    NOTE: getopt is now part of the C library, so if you don't know what
  3.    "Keep this file name-space clean" means, talk to roland@gnu.ai.mit.edu
  4.    before changing it!
  5.  
  6.    Copyright (C) 1987, 88, 89, 90, 91, 92, 1993
  7.        Free Software Foundation, Inc.
  8.  
  9.    This program is free software; you can redistribute it and/or modify it
  10.    under the terms of the GNU General Public License as published by the
  11.    Free Software Foundation; either version 2, or (at your option) any
  12.    later version.
  13.  
  14.  vancing to the next ARGV-element.  */
  15.  
  16. static char *nextchar;
  17.  
  18. /* Callers store zero here to inhibit the error message
  19.    for unrecognized options.  */
  20.  
  21. int opterr = 1;
  22.  
  23. /* Set to an option character which was unrecognized.
  24.    This must be initialized on some systems to avoid linking in the
  25.    system's own getopt implementation.  */
  26.  
  27. int optopt = '?';
  28.  
  29. /* Describe how to deal with options that follow non-option ARGV-elements.
  30.  
  31.    If the caller did not specify anything,
  32.    the default is REQUIRE_ORDER if the environment variable
  33.    POSIXLY_CORRECT is defined, PERMUTE otherwise.
  34.  
  35.    REQUIRE_ORDER means don't recognize them as options;
  36.    stop option processing when the first non-option is seen.
  37.    This is what Unix does.
  38.    This mode of operation is selected by either setting the environment
  39.    variable POSIXLY_CORRECT, or using `+' as the first character
  40.    of the list of option characters.
  41.  
  42.    PERMUTE is the default.  We permute the contents of ARGV as we scan,
  43.    so that eventually all the non-options are at the end.  This allows options
  44.    to be given in any order, even with programs that were not written to
  45.    expect this.
  46.  
  47.    RETURN_IN_ORDER is an option available to programs that were written
  48.    to expect options and other ARGV-elements in any order and that care about
  49.    the ordering of the two.  We describe each non-option ARGV-element
  50.    as if it were the argument of an option with character code 1.
  51.    Using `-' as the first character of the list of option characters
  52.    selects this mode of operation.
  53.  
  54.    The special argument `--' forces an end of option-scanning regardless
  55.    of the value of `ordering'.  In the case of RETURN_IN_ORDER, only
  56.    `--' can cause `getopt' to return EOF with `optind' != ARGC.  */
  57.  
  58. static enum
  59. {
  60.   REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER
  61. } ordering;
  62.  
  63. #if defined(__GNU_LIBRARY__) || defined(macintosh)
  64. /* We want to avoid inclusion of string.h with non-GNU libraries
  65.    because there are many ways it can cause trouble.
  66.    On some systems, it contains special magic macros that don't work
  67.    in GCC.  */
  68. #include <string.h>
  69. #define    my_index    strchr
  70. #define    my_bcopy(src, dst, n)    memcpy ((dst), (src), (n))
  71. #else
  72.  
  73. /* Avoid depending on library functions or files
  74.    whose names are inconsistent.  */
  75.  
  76. char *getenv ();
  77.  
  78. static char *
  79. my_index (str, chr)
  80.      const char *str;
  81.      int chr;
  82. {
  83.   while (*str)
  84.     {
  85.       if (*str == chr)
  86.     return (char *) str;
  87.       str++;
  88.     }
  89.   return 0;
  90. }
  91.  
  92. static void
  93. my_bcopy (from, to, size)
  94.      const char *from;
  95.      char *to;
  96.      int size;
  97. {
  98.   int i;
  99.   for (i = 0; i < size; i++)
  100.     to[i] = from[i];
  101. }
  102. #endif                /* GNU C library.  */
  103.  
  104. /* Handle permutation of arguments.  */
  105.  
  106. /* Describe the part of ARGV that contains non-options that have
  107.    been skipped.  `first_nonopt' is the index in ARGV of the first of them;
  108.    `last_nonopt' is the index after the last of them.  */
  109.  
  110. static int first_nonopt;
  111. static int last_nonopt;
  112.  
  113. /* Exchange two adjacent subsequences of ARGV.
  114.    One subsequence is elements [first_nonopt,last_nonopt)
  115.    which contains all the non-options that have been skipped so far.
  116.    The other is elements [last_nonopt,optind), which contains all
  117.    the options processed since those non-options were skipped.
  118.  
  119.    `first_nonopt' and `last_nonopt' are relocated so that they describe
  120.    the new indices of the non-options in ARGV after they are moved.  */
  121.  
  122. static void
  123. exchange (argv)
  124.      char **argv;
  125. {
  126.   int nonopts_size = (last_nonopt - first_nonopt) * sizeof (char *);
  127.   char **temp = (char **) __alloca (nonopts_size);
  128.  
  129.   /* Interchange the two blocks of data in ARGV.  */
  130.  
  131.   my_bcopy ((char *) &argv[first_nonopt], (char *) temp, nonopts_size);
  132.   my_bcopy ((char *) &argv[last_nonopt], (char *) &argv[first_nonopt],
  133.         (optind - last_nonopt) * sizeof (char *));
  134.   my_bcopy ((char *) temp,
  135.         (char *) &argv[first_nonopt + optind - last_nonopt],
  136.         nonopts_size);
  137.  
  138.   /* Update records for the slots the non-options now occupy.  */
  139.  
  140.   first_nonopt += (optind - last_nonopt);
  141.   last_nonopt = optind;
  142. }
  143.  
  144. /* Scan elements of ARGV (whose length is ARGC) for opti-options previously skipped.  */
  145.  
  146.       while (optind < argc
  147.          && (argv[optind][0] != '-' || argv[optind][1] == '\0')
  148. #ifdef GETOPT_COMPAT
  149.          && (longopts == NULL
  150.              || argv[optind][0] != '+' || argv[optind][1] == '\0')
  151. #endif                /* GETOPT_COMPAT */
  152.          )
  153.         optind++;
  154.       last_nonopt = optind;
  155.     }
  156.  
  157.       /* Special ARGV-element `--' means premature end of options.
  158.      Skip it like a null option,
  159.      then exchange with previous non-options as if it were an option,
  160.      then skip everything else like a non-option.  */
  161.  
  162.       if (optind != argc && !strcmp (argv[optind], "--"))
  163.     {
  164.       optind++;
  165.  
  166.       if (first_nonopt != last_nonopt && last_nonopt != optind)
  167.         exchange ((char **) argv);
  168.       else if (first_nonopt == last_nonopt)
  169.         first_nonopt = optind;
  170.       last_nonopt = argc;
  171.  
  172.       optind = argc;
  173.     }
  174.  
  175.       /* If we have done all the ARGV-elements, stop the scan
  176.      and back over any non-options that we skipped and permuted.  */
  177.  
  178.       if (optind == argc)
  179.     {
  180.       /* Set the next-arg-index to point at the non-options
  181.          that we previously skipped, so the caller will digest them.  */
  182.       if (first_nonopt != last_nonopt)
  183.         optind = first_nonopt;
  184.       return EOF;
  185.     }
  186.  
  187.       /* If we have come to a non-option and did not permute it,
  188.      either stop the scan or describe it to the caller and pass it by.  */
  189.  
  190.       if ((argv[optind][0] != '-' || argv[optind][1] == '\0')
  191. #ifdef GETOPT_COMPAT
  192.       && (longopts == NULL
  193.           || argv[optind][0] != '+' || argv[optind][1] == '\0')
  194. #endif                /* GETOPT_COMPAT */
  195.       )
  196.     {
  197.       if (ordering == REQUIRE_ORDER)
  198.         return EOF;
  199.       optarg = argv[optind++];
  200.       return 1;
  201.     }
  202.  
  203.       /* We have found another option-ARGV-element.
  204.      Start decoding its characters.  */
  205.  
  206.       nextchar = (argv[optind] + 1
  207.           + (longopts != NULL && argv[optind][1] == '-'));
  208.     }
  209.  
  210.   if (longopts != NULL
  211.       && ((argv[optind][0] == '-'
  212.        && (argv[optind][1] == '-' || long_only))
  213. #ifdef GETOPT_COMPAT
  214.       || argv[optind][0] == '+'
  215. #endif                /* GETOPT_COMPAT */
  216.       ))
  217.     {
  218.       const struct option *p;
  219.       char *s = nextchar;
  220.       int exact = 0;
  221.       int ambig = 0;
  222.       const struct option *pfound = NULL;
  223.       int indfound;
  224.  
  225.       while (*s && *s != '=')
  226.     s++;
  227.  
  228.       /* Test all options for either exact match or abbreviated matches.  */
  229.       for (p = longopts, option_index = 0; p->name;
  230.        p++, option_index++)
  231.     if (!strncmp (p->name, nextchar, s - nextchar))
  232.       {
  233.         if (s - nextchar == strlen (p->name))
  234.           {
  235.         /* Exact match found.  */
  236.         pfound = p;
  237.         indfound = option_index;
  238.         exact = 1;
  239.         break;
  240.           }
  241.         else if (pfound == NULL)
  242.           {
  243.         /* First nonexact match found.  */
  244.         pfound = p;
  245.         indfound = option_index;
  246.           }
  247.         else
  248.           /* Second nonexact match found.  */
  249.           ambig = 1;
  250.       }
  251.  
  252.       if (ambig && !exact)
  253.     {
  254.       if (opterr)
  255. #ifdef MPW
  256.         fprintf (stderr, "### %s - Option `%s' is ambiguous\n",
  257. #else
  258.         fprintf (stderr, "%s: option `%s' is ambiguous\n",
  259. #endif
  260.              argv[0], argv[optind]);
  261.       nextchar += strlen (nextchar);
  262.       optind++;
  263.       return '?';
  264.     }
  265.  
  266.       if (pfound != NULL)
  267.     {
  268.       option_index = indfound;
  269.       optind++;
  270.       if (*s)
  271.         {
  272.           /* Don't test has_arg with >, because some C compilers don't
  273.          allow it to be used on enums.  */
  274.           if (pfound->has_arg)
  275.         optarg = s + 1;
  276.           else
  277.         {
  278.           if (opterr)
  279.             {
  280.               if (argv[optind - 1][1] == '-')
  281.             /* --option */
  282.             fprintf (stderr,
  283. #ifdef MPW
  284.                  "### %s - Option `--%s' doesn't allow an argument\n",
  285. #else
  286.                  "%s: option `--%s' doesn't allow an argument\n",
  287. #endif
  288.                  argv[0], pfound->name);
  289.               else
  290.             /* +option or -option */
  291.             fprintf (stderr,
  292. #ifdef MPW
  293.                  "### %s - Option `%c%s' doesn't allow an argument\n",
  294. #else
  295.                  "%s: option `%c%s' doesn't allow an argument\n",
  296. #endif
  297.                  argv[0], argv[optind - 1][0], pfound->name);
  298.             }
  299.           nextchar += strlen (nextchar);
  300.           return '?';
  301.         }
  302.         }
  303.       else if (pfound->has_arg == 1)
  304.         {
  305.           if (optind < argc)
  306.         optarg = argv[optind++];
  307.           else
  308.         {
  309.           if (opterr)
  310.             fprintf (stderr, "%s: option `%s' requires an argument\n",
  311.                  argv[0], argv[optind - 1]);
  312.           nextchar += strlen (nextchar);
  313.           return optstring[0] == ':' ? ':' : '?';
  314.         }
  315.         }
  316.       nextchar += strlen (nextchar);
  317.       if (longind != NULL)
  318.         *longind = option_index;
  319.       if (pfound->flag)
  320.         {
  321.           *(pfound->flag) = pfound->val;
  322.           return 0;
  323.         }
  324.       return pfound->val;
  325.     }
  326.       /* Can't find it as a long option.  If this is not getopt_long_only,
  327.      or the option starts with '--' or is not a valid short
  328.      option, then it's an error.
  329.      Otherwise interpret it as a short option.  */
  330.       if (!long_only || argv[optind][1] == '-'
  331. #ifdef GETOPT_COMPAT
  332.       || argv[optind][0] == '+'
  333. #endif                /* GETOPT_COMPAT */
  334.       || my_index (optstring, *nextchar) == NULL)
  335.     {
  336.       if (opterr)
  337.         {
  338.           if (argv[optind][1] == '-')
  339.         /* --option */
  340. #ifdef MPW
  341.         fprintf (stderr, "### %s - Unrecognized option `--%s'\n",
  342. #else
  343.         fprintf (stderr, "%s: unrecognized option `--%s'\n",
  344. #endif
  345.              argv[0], nextchar);
  346.           else
  347.         /* +option or -option */
  348. #ifdef MPW
  349.         fprintf (stderr, "### %s - Unrecognized option `%c%s'\n",
  350. #else
  351.         fprintf (stderr, "%s: unrecognized option `%c%s'\n",
  352. #endif
  353.              argv[0], argv[optind][0], nextchar);
  354.         }
  355.       nextchar = (char *) "";
  356.       optind++;
  357.       return '?';
  358.     }
  359.     }
  360.  
  361.   /* Look at and handle the next option-character.  */
  362.  
  363.   {
  364.     char c = *nextchar++;
  365.     char *temp = my_index (optstring, c);
  366.  
  367.     /* Increment `optind' when we start to process its last character.  */
  368.     if (*nextchar == '\0')
  369.       ++optind;
  370.  
  371.     if (temp == NULL || c == ':')
  372.       {
  373.     if (opterr)
  374.       {
  375. #if 0
  376.         if (c < 040 || c >= 0177)
  377.           fprintf (stderr, "%s: unrecognized option, character code 0%o\n",
  378.                argv[0], c);
  379.         else
  380.           fprintf (stderr, "%s: unrecognized option `-%c'\n", argv[0], c);
  381. #else
  382.         /* 1003.2 specifies the format of this message.  */
  383.         fprintf (stderr, "%s: illegal option -- %c\n", argv[0], c);
  384. #endif
  385.       }
  386.     optopt = c;
  387.     return '?';
  388.       }
  389.     if (temp[1] == ':')
  390.       {
  391.     if (temp[2] == ':')
  392.       {
  393.         /* This is an option that accepts an argument optionally.  */
  394.         if (*nextchar != '\0')
  395.           {
  396.         optarg = nextchar;
  397.         optind++;
  398.           }
  399.         else
  400.           optarg = 0;
  401.         nextchar = NULL;
  402.       }
  403.     else
  404.       {
  405.         /* This is an option that requires an argument.  */
  406.         if (*nextchar != '\0')
  407.           {
  408.         optarg = nextchar;
  409.         /* If we end this ARGV-element by taking the rest as an arg,
  410.            we must advance to the next element now.  */
  411.         optind++;
  412.           }
  413.         else if (optind == argc)
  414.           {
  415.         if (opterr)
  416.           {
  417. #if 0
  418. #ifdef MPW
  419.             fprintf (stderr, "### %s - Option `-%c' requires an argument\n",
  420. #else
  421.             fprintf (stderr, "%s: option `-%c' requires an argument\n",
  422. #endif
  423.                  argv[0], c);
  424. #else
  425.             /* 1003.2 specifies the format of this message.  */
  426. #ifdef MPW
  427.             fprintf (stderr, "### %s - Option requires an argument -- %c\n",
  428. #else
  429.             fprintf (stderr, "%s: option requires an argument -- %c\n",
  430. #endif
  431.                  argv[0], c);
  432. #endif
  433.           }
  434.         optopt = c;
  435.         if (optstring[0] == ':')
  436.           c = ':';
  437.         else
  438.           c = '?';
  439.           }
  440.         else
  441.           /* We already incremented `optind' once;
  442.          increment it again when taking next ARGV-elt as argument.  */
  443.           optarg = argv[optind++];
  444.         nextchar = NULL;
  445.       }
  446.       }
  447.     return c;
  448.   }
  449. }
  450.  
  451. int
  452. getopt (argc, argv, optstring)
  453.      int argc;
  454.      char *const *argv;
  455.      const char *optstring;
  456. {
  457.   return _getopt_internal (argc, argv, optstring,
  458.                (const struct option *) 0,
  459.                (int *) 0,
  460.                0);
  461. }
  462.  
  463. #endif    /* _LIBC or not __GNU_LIBRARY__.  */
  464.  
  465. #ifdef TEST
  466.  
  467. /* Compile with -DTEST to make an executable for use in testing
  468.    the above definition of `getopt'.  */
  469.  
  470. int
  471. main (argc, argv)
  472.      int argc;
  473.      char **argv;
  474. {
  475.   int c;
  476.   int digit_optind = 0;
  477.  
  478.   while (1)
  479.     {
  480.       int this_option_optind = optind ? optind : 1;
  481.  
  482.       c = getopt (argc, argv, "abc:d:0123456789");
  483.       if (c == EOF)
  484.     break;
  485.  
  486.       switch (c)
  487.     {
  488.     case '0':
  489.     case '1':
  490.     case '2':
  491.     case '3':
  492.     case '4':
  493.     case '5':
  494.     case '6':
  495.     case '7':
  496.     case '8':
  497.     case '9':
  498.       if (digit_optind != 0 && digit_optind != this_option_optind)
  499.         printf ("digits occur in two different argv-elements.\n");
  500.       digit_optind = this_option_optind;
  501.       printf ("option %c\n", c);
  502.       break;
  503.  
  504.     case 'a':
  505.       printf ("option a\n");
  506.       break;
  507.  
  508.     case 'b':
  509.       printf ("option b\n");
  510.       break;
  511.  
  512.     case 'c':
  513.       printf ("option c with value `%s'\n", optarg);
  514.       break;
  515.  
  516.     case '?':
  517.       break;
  518.  
  519.     default:
  520.       printf ("?? getopt returned character code 0%o ??\n", c);
  521.     }
  522.     }
  523.  
  524.   if (optind < argc)
  525.     {
  526.       printf ("non-option ARGV-elements: ");
  527.       while (optind < argc)
  528.     printf ("%s ", argv[optind++]);
  529.       printf ("\n");
  530.     }
  531.  
  532.   exit (0);
  533. }
  534.  
  535. #endif /* TEST */
  536.